package com.imut.lagain.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imut.lagain.entity.HumorMessage;
import com.imut.lagain.service.IHumorMessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 幽默文案控制器
 */

@RestController
@RequestMapping("/humor-messages")
@RequiredArgsConstructor
public class HumorMessageController {
    private static final Logger log = LoggerFactory.getLogger(HumorMessageController.class);

    private final IHumorMessageService humorMessageService;

    /**
     * 创建幽默文案
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createHumorMessage(@RequestBody HumorMessage humorMessage) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            humorMessage.setCreateTime(LocalDateTime.now());
            humorMessage.setUpdateTime(LocalDateTime.now());
            
            boolean success = humorMessageService.save(humorMessage);
            if (success) {
                response.put("success", true);
                response.put("message", "幽默文案创建成功");
                response.put("data", humorMessage);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "幽默文案创建失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            log.error("创建幽默文案失败", e);
            response.put("success", false);
            response.put("message", "创建幽默文案失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取幽默文案分页列表
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getHumorMessages(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String category) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Page<HumorMessage> pageRequest = new Page<>(page, size);
            // 使用正确的方法调用
            IPage<HumorMessage> humorMessages;
            if (category != null && !category.isEmpty()) {
                // 假设category对应moodType字段
                humorMessages = humorMessageService.findByMoodType(category, pageRequest);
            } else {
                humorMessages = humorMessageService.page(pageRequest);
            }
            
            response.put("success", true);
            response.put("data", humorMessages.getRecords());
            response.put("total", humorMessages.getTotal());
            response.put("current", humorMessages.getCurrent());
            response.put("pages", humorMessages.getPages());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取幽默文案列表失败", e);
            response.put("success", false);
            response.put("message", "获取幽默文案列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取随机幽默文案
     */
    @GetMapping("/random")
    public ResponseEntity<Map<String, Object>> getRandomHumorMessage(
            @RequestParam(required = false) String moodType,
            @RequestParam(required = false) String thiefType) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 使用正确的方法调用
            HumorMessage humorMessage = humorMessageService.getRandomHumorMessage(moodType, thiefType);
            
            if (humorMessage != null) {
                response.put("success", true);
                response.put("data", humorMessage);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "暂无幽默文案");
                return ResponseEntity.ok(response);
            }
        } catch (Exception e) {
            log.error("获取随机幽默文案失败", e);
            response.put("success", false);
            response.put("message", "获取随机幽默文案失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 根据ID获取幽默文案
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getHumorMessageById(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            HumorMessage humorMessage = humorMessageService.getById(id);
            
            if (humorMessage != null) {
                response.put("success", true);
                response.put("data", humorMessage);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "幽默文案不存在");
                return ResponseEntity.ok(response);
            }
        } catch (Exception e) {
            log.error("获取幽默文案失败", e);
            response.put("success", false);
            response.put("message", "获取幽默文案失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 更新幽默文案
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateHumorMessage(
            @PathVariable Long id, 
            @RequestBody HumorMessage humorMessage) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            HumorMessage existing = humorMessageService.getById(id);
            if (existing == null) {
                response.put("success", false);
                response.put("message", "幽默文案不存在");
                return ResponseEntity.ok(response);
            }
            
            humorMessage.setId(id);
            humorMessage.setUpdateTime(LocalDateTime.now());
            
            boolean success = humorMessageService.updateById(humorMessage);
            if (success) {
                response.put("success", true);
                response.put("message", "幽默文案更新成功");
                response.put("data", humorMessage);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "幽默文案更新失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            log.error("更新幽默文案失败", e);
            response.put("success", false);
            response.put("message", "更新幽默文案失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 删除幽默文案
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteHumorMessage(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean success = humorMessageService.removeById(id);
            
            if (success) {
                response.put("success", true);
                response.put("message", "幽默文案删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "幽默文案删除失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            log.error("删除幽默文案失败", e);
            response.put("success", false);
            response.put("message", "删除幽默文案失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 批量删除幽默文案
     */
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> batchDeleteHumorMessages(@RequestBody List<Long> ids) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            boolean success = humorMessageService.removeBatchByIds(ids);
            
            if (success) {
                response.put("success", true);
                response.put("message", "幽默文案批量删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "幽默文案批量删除失败");
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            log.error("批量删除幽默文案失败", e);
            response.put("success", false);
            response.put("message", "批量删除幽默文案失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}